package br.com.bikes4bikers.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import br.com.bikes4bikers.dao.AbstractDAO;

@Transactional(readOnly=true, propagation = Propagation.REQUIRED)
public class AbstractDAOImpl<T, ID extends Serializable> implements AbstractDAO<T, ID> {
	
	@SuppressWarnings("unchecked")
	public AbstractDAOImpl() {
		super();
		this.clazz = (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	private EntityManager entityManager;
	
	private final Class<T> clazz;
	
	public Class<T> getObjeClass() {
		return this.clazz;
	}
	

	protected EntityManager getEntityManager() {
		if(entityManager == null)
			throw new IllegalStateException("ERRO");
		return entityManager;
	}
	
	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@SuppressWarnings("unchecked")
	public List<T> listarTodos() {
		StringBuffer sql = new StringBuffer("SELECT obj from ")
		.append(clazz.getSimpleName()).append(" obj");
		Query query = getEntityManager().createQuery(sql.toString());
		return query.getResultList();
	}

	public T inserir(T object) {
		getEntityManager().clear();
		getEntityManager().persist(object);
		return object;
	}

	public T atualizar(T object) {
		getEntityManager().merge(object);
		return object;
	}

	public void excluir(T object) {
		object = getEntityManager().merge(object);
		getEntityManager().remove(object);  
	}

	public List<T> pesquisar(T object) {
		return null;
	}


	public T pesquisarPorId(ID id) {
		return (T) getEntityManager().find(clazz, id) ;
	}
	
	

}
